 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=49 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:08 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Synchronize access to mutable fields
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='field,get,set,synchronized,synchronize,thread,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Synchronize access to mutable fields</div>

<div class='main-body'>
 
<br>In a multi-threaded environment, <i>a mutable field </i>must always
appear in a <tt>synchronized</tt> section of code (except inside a constructor).
For example, in a multi-threaded environment, all <tt>get</tt> and <tt>set</tt>
methods for mutable fields must be <tt>synchronized</tt>. This includes
primitive fields.
<p>Most classes do not need to be designed for operation in a multi-threaded
environment, and can ignore these considerations.
<p>If an object does need to live in a multi-threaded environment, however,
then a significant amount of care must be taken to ensure that it is correctly
designed.
<p>If an object is <a href="TopicActiond838-2.html">immutable</a>, then it is automatically
<a href="TopicAction234f-2.html">thread-safe</a>. If it is mutable, then extra steps
must be taken to ensure thread-safety : every use of every mutable field
must appear in a <tt>synchronized</tt> section of code.
<p>Here, <i>mutable field</i> simply means a field which might change in
any way, after the initial construction of the object. (Objects are never
shared between threads until after the object is fully created.) For example,
<ul>
<li>
an <tt>int</tt> field that changes its value some time after the constructor
completes</li>

<li>
a <tt>Date</tt> field that changes state some time after the constructor
completes, to represent a different date from the original</li>

<li>
any object field that is "pointed" to a new object, some time after the
constructor completes</li>
</ul>
Remember that all <i>local</i> variables declared in the body of a method
are never shared between threads, and so have no thread-safety considerations.
<p>It is a misconception that all mutable primitives except <tt>long</tt>
and <tt>double</tt> do not need <tt>synchronized</tt> access.

<p><b>Example</b>

<p>Note that even the <tt>get</tt> of the <tt>int</tt> field is a <tt>synchronized</tt>
method.
<br>
<PRE>

<span class='keyword'>import</span> java.util.Date;

<span class='comment'>/**
* This class is mutable, but thread-safe : the caller never
* needs to perform external synchronization, except when multiple calls
* need to be treated as a single unit.
*
* This class illustrates the three possible cases for fields :
*&lt;ul&gt;
* &lt;li&gt; a primitive (int)
* &lt;li&gt; an immutable object (String)
* &lt;li&gt; a mutable object (Date)
*&lt;/ul&gt;
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> MutablePlanet {

  <span class='keyword'>public</span> MutablePlanet (<span class='keyword'>int</span> aId, String aName, Date aDateOfDiscovery) {
     fId = aId;
     fName = aName;
     <span class='comment'>//Make a private copy of aDateOfDiscovery.
</span>     <span class='comment'>//This is the only way to keep the fDateOfDiscovery
</span>     <span class='comment'>//field private, and shields this class from any changes
</span>     <span class='comment'>//to the original aDateOfDiscovery object which might be
</span>     <span class='comment'>//made by the caller.
</span>     fDateOfDiscovery = <span class='keyword'>new</span> Date(aDateOfDiscovery.getTime());
  }

  <span class='keyword'>public</span> <span class='keyword'>synchronized</span> <span class='keyword'>int</span> getId() {
     <span class='keyword'>return</span> fId;
  }
  <span class='keyword'>public</span> <span class='keyword'>synchronized</span> <span class='keyword'>void</span> setId( <span class='keyword'>int</span> aNewId ) {
    fId = aNewId;
  }

  <span class='keyword'>public</span> <span class='keyword'>synchronized</span> String getName() {
    <span class='keyword'>return</span> fName;
  }
  <span class='keyword'>public</span> <span class='keyword'>synchronized</span> <span class='keyword'>void</span> setName( String aNewName ) {
    fName = aNewName;
  }

  <span class='comment'>/**
  * Returns a defensive copy of the field.
  * The caller of this method can do anything they want with the
  * returned Date object, without affecting the internals of this
  * class in any way.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>synchronized</span> Date getDateOfDiscovery() {
    <span class='keyword'>return</span> <span class='keyword'>new</span> Date(fDateOfDiscovery.getTime());
  }
  <span class='keyword'>public</span> <span class='keyword'>synchronized</span> <span class='keyword'>void</span> setDateOfDiscovery(Date aNewDiscoveryDate) {
    <span class='comment'>//change the state of the mutable Date field
</span>    fDateOfDiscovery.setTime(aNewDiscoveryDate.getTime());
  }

  <span class='comment'>// PRIVATE //
</span>
  <span class='comment'>/**
  * A primitive field.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>int</span> fId;

  <span class='comment'>/**
  * An immutable object field.
  * Strings never alter state after construction.
  */</span>
  <span class='keyword'>private</span> String fName;

  <span class='comment'>/**
  * A mutable object field.
  * The state of a Date can change after construction.
  */</span>
  <span class='keyword'>private</span> Date fDateOfDiscovery;
}
 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicActiond838-2.html?Id=29'>Immutable objects</a> <br>
 
  
  <a href='TopicAction234f-2.html?Id=48'>Document thread safety</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='49'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=49 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:08 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
